package com.xiaomo.gitee.datamanager.service.tag.impl;

import com.xiaomo.gitee.datamanager.aspect.log.anno.SysLog;
import com.xiaomo.gitee.datamanager.mapper.CategoryTagMapper;
import com.xiaomo.gitee.datamanager.mapper.ImageTagMapper;
import com.xiaomo.gitee.datamanager.entity.Tags;
import com.xiaomo.gitee.datamanager.service.tag.TagsService;
import com.xiaomo.gitee.datamanager.mapper.TagsMapper;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class TagsServiceImpl implements TagsService{

    private final TagsMapper tagsMapper;
    private final ImageTagMapper imageTagMapper;
    private final CategoryTagMapper categoryTagMapper;
    private final ImageTagServiceImpl imageTagService;


    @Override
    @SysLog("创建标签")
    public int createTag(String name) {
        if (tagsMapper.selectOneByContent(name) != null) {
            return 2;
        }
        Tags tag = new Tags(name);
        tagsMapper.insert(tag);

        MDC.put("标签",tag.getContent());
        MDC.put("标签Id",tagsMapper.selectOneByContent(name).getId().toString());

        return 0;
    }


    @Override
    public Tags getTagById(Long id) {
        return tagsMapper.selectById(id);
    }

    @Override
    public List<Tags> getAllTags() {
        return tagsMapper.selectAll();
    }

    @Override
    @SysLog("删除标签")
    public void deleteTag(List<Long> idList) {
        idList.forEach(id -> {
            categoryTagMapper.deleteByTagId(id);
            imageTagMapper.deleteByTagId(id);
            tagsMapper.deleteById(id);
        });


        MDC.put("标签Id",idList.toString());

    }

    /**
     *
     * @param newName
     * @param id
     * @return 1 已存在相同名称
     * @return 2 名字与原来相同
     * @return 0 成功
     */
    @Override
    @SysLog("更新标签信息")
    public int updateTag(String newName, Long id) {
        if (tagsMapper.selectById(id).getContent().equals(newName)) {
            return 2;
        }
        if (tagsMapper.selectOneByContent(newName) != null) {
            return 1;
        }
        tagsMapper.updateContentById(newName,id);

        MDC.put("标签Id",id.toString());
        MDC.put("新名称",newName);

        return 0;
    }
}




